import React from 'react';
import { connect } from 'dva/index';
import { Select } from 'antd';
import debounce from 'lodash/debounce';
const R = require('ramda');
const Option = Select.Option;


class CompanySelect extends React.Component {
    constructor(props) {
        super(props);
        this.handleAllCst = debounce(this.handleAllCst, 2400); //去抖
        this.initData(props.value, true);
    }

    componentWillReceiveProps(nextProps) {
        if (!R.equals(this.props.value)(nextProps.value)) {
            this.initData(nextProps.value)
        }
    }

    initData = (value, flag) => {
        value = R.isNil(value) ? [] : value;
        if (flag) {
            this.state = {
                company: [],
                illegalValue: false,	//是否非法value，如果是，则渲染时把value去掉
                values: undefined	//被选中的值
            }
        }
    }

    handleAllCst = (value) => {
        if (!R.isEmpty(value)) {
            this.props.dispatch({
                type: 'company/getListByNameAndCusNo',
                payload: {
                    nameOrCusNo: value,
                    onSuccess: (source) => {
                        this.setState({ company: source})
                    }
                }
            })
        }
    }

    render() {
        let value = this.props.value;
        if (this.state.illegalValue && value && value instanceof Array) {
            value = value.filter(item => Number.isInteger(Number.parseInt(item)));
        }
        let companys = Array.from(new Set(this.state.company ? this.state.company : []));
        return (
            <Select
                showSearch size="large"
                allowClear
                style={this.props.style}
                {...R.omit(['app, value'])(this.props) }
                value={value}
                placeholder="可根据客户号或公司名称搜索"
                filterOption={false}
                onSearch={this.handleAllCst.bind(this)}
            >
                {
                    (companys).map(item => {
                        return (<Option value={item.id} key={item.id}>{item.companyName}</Option>);
                    })
                }
            </Select>
        );
    }
}

export default connect(({ company }) => ({ company }))(CompanySelect)